New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

als-lang

Package Overview
Dependencies
Maintainers
0
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

als-lang

Lang is a lightweight library for handling automatic text translations with customizable markers. It works both in Node.js and browser environments.

  • 1.3.0
  • latest
  • npm
  • Socket score

Version published
Weekly downloads
11
increased by57.14%
Maintainers
0
Weekly downloads
 
Created
Source

als-Lang Library Documentation

Lang is a lightweight library for handling automatic text translations with customizable markers. It works both in Node.js and browser environments.

Change Log for 1.2.0

  • Error Handling Update:
    Previous behavior of throwing an error when the number of translations did not match the number of languages has been replaced. Now, missing translations are filled with empty strings ('').

  • New Methods Added:

    1. add(items): Adds new key-value pairs to the existing dictionary. For each key, translations are added for the existing languages, with missing translations filled as empty strings.
    2. merge(data): Creates a new Lang instance by merging the current instance with the provided data. Combines dictionaries, with priority given to the current instance's data when conflicts arise.

Installation

npm install lang-library

Initialization

Import the Library

In Node.js:

const Lang = require('lang-library');

In the browser:

<script src="/node_modules/als-lang/lang.js"></script>
<!-- or Minified: -->
<script src="/node_modules/als-lang/lang.min.js"></script>

Create an Instance

const data = {
  dictionary: {
    'Hello, world!': ['Привет, мир!', 'Hola, mundo!'],
    'How are you?': ['Как дела?', '¿Cómo estás?'],
  },
  langs: ['ru', 'es'],
};

const translator = new Lang(data, 'ru'); // Default language is Russian
  • dictionary: An object where keys are original phrases, and values are arrays of translations for each language.
  • langs: An array of language codes (e.g., ['ru', 'es']).
  • defaultLang: (Optional) The fallback language code when a translation is unavailable. Defaults to 'en'.

Methods

dictionaryFn(lang)

Returns a function that takes text and translates it into the specified language if a translation exists. If no translation is available, it returns the original text.

Parameters:
  • lang: The target language code.
Example:
const translator = new Lang(data, 'ru');
const translate = translator.dictionaryFn('ru');

console.log(translate('Hello, world!')); 
// Output: Привет, мир!

console.log(translate('Unknown phrase'));
// Output: Unknown phrase

replace(text, lang)

Replaces all occurrences of text wrapped in the defined markers (~...~) with the corresponding translation. Internally uses the dictionaryFn method to fetch translations.

Parameters:
  • text: The string containing text wrapped in markers (e.g., ~Hello, world!~).
  • lang: The target language code for the translation.
Example:
const text = 'Welcome! ~Hello, world!~ ~How are you?~';
console.log(translator.replace(text, 'ru'));
// Output: Welcome! Привет, мир! Как дела?

console.log(translator.replace(text, 'es'));
// Output: Welcome! Hola, mundo! ¿Cómo estás?

If the translation for the specified language is not available, the original text is returned:

console.log(translator.replace(text, 'fr'));
// Output: Welcome! Hello, world! How are you?

Custom Markers

By default, ~ is used as the start and end marker. You can change it globally:

Lang._start = '{{';
Lang._end = '}}';

const customTranslator = new Lang(data, 'ru');
const text = 'Welcome! {{Hello, world!}} {{How are you?}}';
console.log(customTranslator.replace(text, 'ru'));
// Output: Welcome! Привет, мир! Как дела?

Note: Markers must be the same for all instances.

Error Handling

  1. Invalid Language Array:
    • If langs is not an array, an error will be thrown:
    const invalidData = { dictionary: {}, langs: 'ru, es' };
    new Lang(invalidData); // Error: Langs must be an array
    

Examples

Basic Translation

const data = {
  dictionary: {
    'Welcome!': ['Добро пожаловать!', '¡Bienvenidos!'],
  },
  langs: ['ru', 'es'],
};

const translator = new Lang(data, 'ru');
console.log(translator.replace('~Welcome!~', 'ru'));
// Output: Добро пожаловать!

Fallback Language

const translator = new Lang(data, 'es'); // Default is Spanish
console.log(translator.replace('~Welcome!~', 'fr')); 
// Output: ¡Bienvenidos!

Empty Dictionary

const emptyData = { dictionary: {}, langs: ['ru', 'es'] };
const translator = new Lang(emptyData);

console.log(translator.replace('~Unknown phrase~', 'ru'));
// Output: Unknown phrase

Method add(items)

Description

The add method allows you to dynamically add new translations to the existing Lang instance. If a translation for a specific language is missing, it is automatically filled with an empty string ('').

Parameters:
  • items: An object where keys are original phrases, and values are arrays of translations for each language.
Example Usage:
const lang = new Lang({
  langs: ['en', 'es'],
  dictionary: { hello: ['Hello', 'Hola'] },
});

lang.add({
  goodbye: ['Goodbye', 'Adiós'],
  world: ['World'], // Spanish translation missing
});

console.log(lang.langs);
// Output:
// {
//   en: { hello: 'Hello', goodbye: 'Goodbye', world: 'World' },
//   es: { hello: 'Hola', goodbye: 'Adiós', world: '' },
// }

Method merge(data)

Description

The merge method creates a new Lang instance by combining the current instance's data with the provided data. The method ensures that translations from the current instance take precedence in case of conflicts.

Parameters:
  • data: An object with langs (array) and dictionary (object) properties to merge into the current instance or another Lang instance.
Example Usage:
const lang1 = new Lang({
  langs: ['en', 'es'],
  dictionary: { hello: ['Hello', 'Hola'] },
});

const mergedLang = lang1.merge({
  langs: ['en', 'fr'], // Adding French
  dictionary: { goodbye: ['Goodbye', 'Au revoir'], hello: ['Hi', 'Salut'] },
});

// Or

const mergedLang = lang1.merge(new Lang({
  langs: ['en', 'fr'], // Adding French
  dictionary: { goodbye: ['Goodbye', 'Au revoir'], hello: ['Hi', 'Salut'] },
}));


console.log(mergedLang.langs);
// Output:
// {
//   en: { hello: 'Hello', goodbye: 'Goodbye' },
//   es: { hello: 'Hola', goodbye: '' },
//   fr: { hello: 'Salut', goodbye: 'Au revoir' },
// }

Notes

  • The library works seamlessly in both Node.js and browser environments.
  • Translations should be provided as arrays with values matching the order of langs.
  • Custom markers (start and end) must be globally consistent for all instances.
    • The add method allows dynamic updates to the dictionary, filling missing translations with empty strings ('').
  • The merge method creates a new Lang instance by combining data from two sources, with the current instance's data taking precedence.

FAQs

Package last updated on 28 Dec 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc